/**
 * 支付相关服务
 */

const util = require('../utils/util.js');
const api = require('../api/api.js');

/**
 * 判断用户是否登录
 */
function payOrder(orderId) {
  console.log(orderId);

  let code = null;
  return new Promise(function (resolve, reject) {
    return util.login().then((res) => {
      console.log(res.code);
      // 获取openID
      util.request(api.OpenidGet + '.' + res.code, {}).then(function (openIdRes) {
        console.log(openIdRes);
        // 判断openId是否获取成功
        if (openIdRes.openid != undefined && openIdRes.errcode == undefined) {
          // 有一点需要注意 询问用户 是否授权 那提示 是这API发出的
          console.log(orderId);
          util.request(api.PayPrepayId, {
            order: orderId,
            openid: openIdRes.openid,
            code: 'wxpay.web'
          }, 'post').then((res) => {
            console.log(res);
            if (res.error_code === 0 && res.wx.return_code != 'FAIL' && res.wx.result_code != 'FAIL') {
              const payParam = res.wx;
              wx.requestPayment({
                'timeStamp': payParam.timeStamp,
                'nonceStr': payParam.nonceStr,
                'package': payParam.package,
                'signType': 'MD5',
                'paySign': payParam.paySign,
                'success': function (res) {
                  resolve(res);
                },
                'fail': function (res) {
                  reject(res);
                },
                'complete': function (res) {
                  reject(res);
                }
              });
            } else {
              reject(res.errmsg);
            }
          });
        };
      });
    });
  });
}

module.exports = {
  payOrder,
};











